import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 导入登录页组件
import login from '@/views/login/index.vue';
import layout from '@/views/layout/index.vue';
import home from '@/views/home/index.vue';
import my from '@/views/my/index.vue';
import ask from '@/views/ask/index.vue';
import video from '@/views/video/index.vue';
import edit from '@/views/my/edit.vue';

// 设置路由规则
const routes = [{
    name: 'login',
    path: '/login',
    component: login
  }, {
    path: '',
    redirect: '/login'
  },
  {
    name: 'edit',
    path: '/my/edit',
    component: edit,
    meta: {
      allowable: true
    }
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    redirect: '/layout/home',
    children: [{
        path: '/',
        redirect: 'home'
      },
      {
        name: 'home',
        path: 'home',
        component: home
      },
      {
        name: 'my',
        path: 'my',
        component: my,
        meta: {
          allowable: true
        }
      },
      {
        name: 'ask',
        path: 'ask',
        component: ask
      },
      {
        name: 'video',
        path: 'video',
        component: video
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

import store from '@/store/index.js';

// 设置导航守卫
router.beforeEach((to, from, next) => {
  if (to.meta.allowable) {
    if (store.state.tokenObj.token) {
      next()
    } else {
      Vue.prototype.$toast.fail('请登录')
      next('/login?back=' + to.path)
    }
  }
  next()
})

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error)
}

export default router